<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="站点编号" prop="stationCode">
        <el-input v-model="queryParams.stationCode" placeholder="请输入站点编号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="站点名称" prop="stationName">
        <el-input v-model="queryParams.stationName" placeholder="请输入站点名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['manage:measurementroom:add']">新增</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="measurementroomList" @selection-change="handleSelectionChange">
      <el-table-column label="序号" align="center" type="index" prop="id" />
      <el-table-column label="站点编号" align="center" prop="stationCode" />
      <el-table-column label="站点名称" align="center" prop="stationName" />
      <!-- <el-table-column label="关联管道名称" align="center" prop="pipelineName" /> -->
      <!-- <el-table-column label="站点坐标" align="center" prop="locationFormatted" />
      <el-table-column label="所属作业区" align="center" prop="operationArea" />
      <el-table-column label="所属区块" align="center" prop="block" />
      <el-table-column label="所属总接口数" align="center" prop="totalInterfaces" />
      <el-table-column label="已使用接口数" align="center" prop="usedInterfaces" />
      <el-table-column label="预留接口数" align="center" prop="reservedInterfaces" />
      <el-table-column label="下游脱水站" align="center" prop="downstreamDehydrationStation" /> -->
      <el-table-column label="设计处理量" align="center" prop="capacity" />
      <el-table-column label="备注" align="left" prop="remark">
        <template #default="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.remark" placement="top">
            <div class="remark-cell">{{ scope.row.remark }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" @click="getAll(scope.row)"
            v-hasPermi="['manage:measurementroom:list']">查看详情</el-button>
          <el-button link type="primary" @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:measurementroom:edit']">修改</el-button>
          <el-button link type="primary" @click="handleDelete(scope.row)"
            v-hasPermi="['manage:measurementroom:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改计量间对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="measurementroomRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="站点编号" prop="stationCode">
          <el-input v-model="form.stationCode" placeholder="请输入站点编号" />
        </el-form-item>
        <el-form-item label="站点名称" prop="stationName">
          <el-input v-model="form.stationName" placeholder="请输入站点名称" />
        </el-form-item>
        <el-form-item label="经度" prop="longitude">
          <el-input v-model="form.longitude" placeholder="请输入经度" />
        </el-form-item>
        <el-form-item label="纬度" prop="latitude">
          <el-input v-model="form.latitude" placeholder="请输入纬度" />
        </el-form-item>
        <el-form-item label="所属作业区" prop="operationArea">
          <el-select v-model="form.operationArea" placeholder="请选择所属作业区">
            <el-option v-for="dict in operation_area" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属区块" prop="block">
          <el-select v-model="form.block" placeholder="请选择所属区块">
            <el-option v-for="dict in block" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="总接口数" prop="totalInterfaces">
          <el-input v-model="form.totalInterfaces" placeholder="请输入总接口数" />
        </el-form-item>
        <el-form-item label="已使用接口数" prop="usedInterfaces">
          <el-input v-model="form.usedInterfaces" placeholder="请输入已使用接口数" />
        </el-form-item>
        <el-form-item label="预留接口数" prop="reservedInterfaces">
          <el-input v-model="form.reservedInterfaces" placeholder="请输入预留接口数" />
        </el-form-item>
        <el-form-item label="下游脱水站" prop="reservedInterfaces">
          <el-input v-model="form.downstreamDehydrationStation" placeholder="请输入下游脱水站" />
        </el-form-item>
        <el-form-item label="设计处理量" prop="capacity">
          <el-input v-model="form.capacity" placeholder="请输入设计处理量" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog title="计量间详情" v-model="measurementroomOpen" width="500px" append-to-body>
      <el-row>
        <el-col :span="30">计量间编号:{{ form.stationCode }}</el-col>
      </el-row>
      <el-row>
        <el-col :span="30">计量间名称:{{ form.stationName }}</el-col>
      </el-row>
      <el-row>
        <el-col :span="30">创建时间:{{ form.createTime }}</el-col>
      </el-row>
      <el-row>
        <el-col :span="30">经度：{{ form.longitude }}，纬度：{{ form.latitude }}</el-col>
      </el-row>
      <el-row>
        <el-col :span="30">所属作业区：{{ form.operationArea }}</el-col>
      </el-row>
      <el-row>
        <el-col :span="30">所属区块：{{ form.block }}</el-col>
      </el-row>
      <el-row>
        <el-col :span="30">总接口数：{{ form.totalInterfaces }}</el-col>
      </el-row>
      <el-row>
        <el-col :span="30">已使用接口数：{{ form.usedInterfaces }}</el-col>
      </el-row>
      <el-row>
        <el-col :span="30">预留接口数：{{ form.reservedInterfaces }}</el-col>
      </el-row>
      <el-row>
        <el-col :span="30">下游脱水站：{{ form.downstreamDehydrationStation }}</el-col>
      </el-row>

      <el-divider content-position="center">关联管线编号</el-divider>
      <el-row :gutter="10" class="mb8"></el-row>
      <el-table :data="pipeCodeList" ref="pineline">
        <el-table-column label="序号" align="center" type="index" />
        <el-table-column label="管线编号">
          <template #default="scope">
            <span>{{ scope.row }}</span> <!-- 直接显示每个编号 -->
          </template>
        </el-table-column>
      </el-table>

      <el-divider content-position="center">关联油水井编号</el-divider>
      <el-row :gutter="10" class="mb8"></el-row>
      <el-table :data="wellCodeList">
        <el-table-column label="序号" align="center" type="index" />
        <el-table-column label="油水井编号">
          <template #default="scope">
            <span>{{ scope.row }}</span> <!-- 直接显示每个油水井编号 -->
          </template>
        </el-table-column>
      </el-table>


    </el-dialog>

  </div>
</template>

<script setup name="Measurementroom">
import { listMeasurementroom, getMeasurementroom, delMeasurementroom, addMeasurementroom, updateMeasurementroom } from "@/api/manage/measurementroom";

const { proxy } = getCurrentInstance();

const measurementroomList = ref([]);
const open = ref(false);

const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    stationCode: null,
    stationName: null,
  },
  rules: {
    stationCode: [
      { required: true, message: "站点编号不能为空", trigger: "blur" }
    ],
    stationName: [
      { required: true, message: "站点名称不能为空", trigger: "blur" }
    ],
    capacity: [
      { required: true, message: "设计处理量不能为空", trigger: "blur" }
    ],
    operationArea: [
      { required: true, message: "所属作业区不能为空", trigger: "change" }
    ],
    block: [
      { required: true, message: "所属区块不能为空", trigger: "change" }
    ],
    totalInterfaces: [
      { required: true, message: "总接口数不能为空", trigger: "change" }
    ],
    usedInterfaces: [
      { required: true, message: "已使用接口数不能为空", trigger: "change" }
    ],
    reservedInterfaces: [
      { required: true, message: "预留接口数不能为空", trigger: "change" }
    ],
    downstreamDehydrationStation: [
      { required: true, message: "下游脱水站不能为空", trigger: "change" }
    ],
    pipelineId: [
      { required: true, message: "关联管线名称不能为空", trigger: "change" }
    ],
    longitude: [
      { required: true, message: "经度不能为空", trigger: "blur" },
      { validator: validateLongitude, trigger: "blur" }
    ],
    latitude: [
      { required: true, message: "纬度不能为空", trigger: "blur" },
      { validator: validateLatitude, trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);
import { listPipeline } from "@/api/manage/pipeline";
import { loadAllParams } from "@/api/page"
const { operation_area } = proxy.useDict('operation_area');
const { block } = proxy.useDict('block');

//查询管道名称
const pipelineList = ref([]);
function getPipelineList() {
  listPipeline(loadAllParams).then(response => {
    pipelineList.value = response.rows;
  });
}
/** 查询计量间列表 */
function getList() {
  loading.value = true;
  listMeasurementroom(queryParams.value).then(response => {
    measurementroomList.value = response.rows.map(row => {
      const location = row.location;
      if (location && location.startsWith('POINT')) {
        const [longitude, latitude] = location.match(/-?\d+(\.\d+)?/g).map(Number);
        return {
          ...row,
          locationFormatted: `经度: ${longitude}, 纬度: ${latitude}`
        };
      }
      return row;
    })
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    stationCode: null,
    stationName: null,
    location: null,
    capacity: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    remark: null
  };
  proxy.resetForm("measurementroomRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加计量间";
}


/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getMeasurementroom(_id).then(response => {
    form.value = response.data;
    const location = response.data.location;
    if (location && location.startsWith('POINT')) {
      const [longitude, latitude] = location.match(/-?\d+(\.\d+)?/g).map(Number);
      form.value.longitude = longitude;
      form.value.latitude = latitude;
    }
    open.value = true;
    title.value = "修改计量间";
  });
}

/**查看详情按钮操作 */
const measurementroomOpen = ref(false);
const pipeCodeList = ref([]);
const wellCodeList = ref([]);


function getAll(row) {
  getMeasurementroom(row.id).then(response => {
    form.value = response.data;
    pipeCodeList.value = response.data.pipeCode
    wellCodeList.value = response.data.wellCode;

    // 提取经纬度
    if (response.data.location) {
      const locationMatch = response.data.location.match(/POINT \((-?\d+(\.\d+)?)\s+(-?\d+(\.\d+)?)\)/);
      if (locationMatch) {
        form.value.longitude = parseFloat(locationMatch[1]);
        form.value.latitude = parseFloat(locationMatch[3]);
      }
    }

    measurementroomOpen.value = true;
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["measurementroomRef"].validate(valid => {
    form.value.location = `POINT (${form.value.longitude} ${form.value.latitude})`;
    delete form.value.longitude;
    delete form.value.latitude;

    if (valid) {
      if (form.value.id != null) {
        updateMeasurementroom(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addMeasurementroom(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除计量间编号为"' + _ids + '"的数据项？').then(function () {
    return delMeasurementroom(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/measurementroom/export', {
    ...queryParams.value
  }, `measurementroom_${new Date().getTime()}.xlsx`)
}

//处理经度
function validateLongitude(rule, value, callback) {
  if (!value) {
    callback(new Error('经度不能为空'));
  } else if (!/^(-?\d{1,3}(\.\d{1,4})?)$/.test(value)) {
    callback(new Error('请输入有效的经度，小数点后最多四位'));
  } else {
    const longitude = parseFloat(value);
    if (longitude < -180 || longitude > 180) {
      callback(new Error('经度范围应在 -180 到 180 之间'));
    } else {
      callback();
    }
  }
}
//处理维度
function validateLatitude(rule, value, callback) {
  if (!value) {
    callback(new Error('纬度不能为空'));
  } else if (!/^(-?\d{1,2}(\.\d{1,4})?)$/.test(value)) {
    callback(new Error('请输入有效的纬度，小数点后最多四位'));
  } else {
    const latitude = parseFloat(value);
    if (latitude < -90 || latitude > 90) {
      callback(new Error('纬度范围应在 -90 到 90 之间'));
    } else {
      callback();
    }
  }
}

getPipelineList()
getList();
</script>
<style scoped>
.remark-cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
}
</style>